﻿using System;
using System.Xml;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TemplatesPlugin {
    public partial class TemplateBrowse : Form {
        public TemplateBrowse() {
            InitializeComponent();
        }

        /// <summary>
        /// Read templates file and fill the list
        /// </summary>
        private void readTemplates() {
            try {
                XmlDocument xmlFile = new XmlDocument();
                xmlFile.Load(Plugin.templateFile);

                templateList.Groups.Clear();
                foreach (XmlNode node in xmlFile.SelectNodes("NotepadX/Groups/Group")) {
                    templateList.Groups.Add(new ListViewGroup(node.Attributes.GetNamedItem("id").InnerText, node.Attributes.GetNamedItem("name").InnerText));
                }
                templateList.Items.Clear();
                foreach (XmlNode node in xmlFile.SelectNodes("NotepadX/Templates/Template")) {
                    ListViewItem newItem = new ListViewItem(node.Attributes.GetNamedItem("name").InnerText, 0);
                    templateList.Items.Add(newItem);
                    if (node.Attributes.GetNamedItem("group").InnerText != String.Empty) {
                        newItem.Group = templateList.Groups[node.Attributes.GetNamedItem("group").InnerText];
                    }
                    newItem.SubItems.Add(node.Attributes.GetNamedItem("description").InnerText);
                    newItem.SubItems.Add(node.Attributes.GetNamedItem("extension").InnerText);
                    newItem.SubItems.Add(node.Attributes.GetNamedItem("filename").InnerText);
                    newItem.SubItems.Add(node.Attributes.GetNamedItem("replaceWithFileName").InnerText);
                    xmlFile = null;
                }
            } catch (Exception) {
            }
        }

        private void TemplateBrowse_Load(object sender, EventArgs e) {
            if (Notepad_X.Static.MainInstance.IconsCollection.Images.ContainsKey("File")) {
                this.Icon = System.Drawing.Icon.FromHandle(new System.Drawing.Bitmap(Notepad_X.Static.MainInstance.IconsCollection.Images["File"]).GetHicon());
                templateImageList.Images.Clear();
                templateImageList.Images.Add(Notepad_X.Static.MainInstance.IconsCollection.Images["File"]);
            } else {
                this.ShowIcon = false;
            }
         
            Notepad_X.Components.Static.UpdatePanel(controlPanel,true);
            Notepad_X.Components.Static.UpdatePanel(groupsPanel, true);
            Notepad_X.Components.Static.UpdatePanel(editPanel, true);

            readTemplates();
        }

        private void cancel_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void open_Click(object sender, EventArgs e) {
                 if (templateList.SelectedItems.Count > 0) {
            //Selected info;
            //Filename
            //FilePath
            //Extension
            //int id //= Notepad_X.Static.MainInstance.system_new();
                    int id= Notepad_X.Static.MainInstance.system_open(
                         System.IO.Path.Combine(Plugin.templateDirectory, templateList.SelectedItems[0].SubItems[3].Text));
                    if (id == -1) return;
                    Notepad_X.Static.MainInstance.Documents[id].path = String.Empty;
                    Notepad_X.Static.MainInstance.Panel.SelectedTab.Text = filename.Text;
                     String ClearFileName =    filename.Text = filename.Text.Remove(filename.Text.LastIndexOf(".") );
                     if (templateList.SelectedItems[0].SubItems[4].Text != String.Empty) {
                         while (Notepad_X.Static.MainInstance.Documents[id].text.Contains(templateList.SelectedItems[0].SubItems[4].Text)) {
                             Notepad_X.Static.MainInstance.Documents[id].replace(templateList.SelectedItems[0].SubItems[4].Text, ClearFileName);
                         }
                     }
            //OR System  open and then clear filePath and change name to current

            this.Close();
                 }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e) {

            if (controlPanel.Visible) {     //Select Mode
                open.Enabled = (templateList.SelectedItems.Count > 0);
                if (templateList.SelectedItems.Count > 0) {
                    if (filename.Text.Contains(".")) {
                        filename.Text = filename.Text.Remove(filename.Text.LastIndexOf(".")) + templateList.SelectedItems[0].SubItems[2].Text; ;
                    } else if (!String.IsNullOrEmpty(filename.Text)) {
                        filename.Text = filename.Text + templateList.SelectedItems[0].SubItems[2].Text; ;
                    }
                }
            } else {  //Edit Mode 
                editRemove.Enabled = editApply.Enabled = (templateList.SelectedItems.Count > 0);
                if (templateList.SelectedItems.Count > 0) {
                    ListViewItem selectedItem = templateList.SelectedItems[0];
                    editName.Text = selectedItem.Text;
                    if (selectedItem.Group == null) {
                        editGroup.SelectedItem = "None";
                    } else {
                        editGroup.SelectedItem = selectedItem.Group.Name;
                    }
                    editDescription.Text = selectedItem.SubItems[1].Text;
                    editExtension.Text = selectedItem.SubItems[2].Text;
                    editFileName.Text = selectedItem.SubItems[3].Text;
                    editReplace.Text = selectedItem.SubItems[4].Text;
                } else {
                    editName.Text = editDescription.Text = editExtension.Text = editFileName.Text = editReplace.Text = String.Empty;
                    editGroup.SelectedIndex = 0;
                }
            }
          
        }

        private void groupsSave_Click(object sender, EventArgs e) {
            XmlTextWriter xmlFile = new XmlTextWriter(Plugin.templateFile, System.Text.Encoding.UTF8);
            xmlFile.Formatting = Formatting.Indented;
            xmlFile.WriteStartElement("NotepadX");

       
            xmlFile.WriteStartElement("Groups");
         

          

            foreach (ListViewItem item in groupsList.Items) {
                xmlFile.WriteStartElement("Group");
                xmlFile.WriteAttributeString("id", item.Text);
                xmlFile.WriteAttributeString("name",item.SubItems[1].Text);
                xmlFile.WriteEndElement();
            }
            xmlFile.WriteEndElement(); // End of Groups
            xmlFile.WriteStartElement("Templates");

            foreach (ListViewItem item in templateList.Items) {
                xmlFile.WriteStartElement("Template");
                xmlFile.WriteAttributeString("name", item.Text);
                xmlFile.WriteAttributeString("group", item.Group.Name);
                xmlFile.WriteAttributeString("description", item.SubItems[1].Text);
                xmlFile.WriteAttributeString("extension", item.SubItems[2].Text);
                xmlFile.WriteAttributeString("filename", item.SubItems[3].Text);
                xmlFile.WriteAttributeString("replaceWithFileName", item.SubItems[4].Text);
                xmlFile.WriteEndElement();
            }
            xmlFile.WriteEndElement(); // End of Templates
       

            xmlFile.WriteEndElement();
            xmlFile.Flush();
            xmlFile.Close();


            templateList.Visible = true;
            groupsPanel.Visible =false ;
            controlPanel.Visible = true;
            templateList.Select();
            readTemplates();
        }

        private void groupsCancel_Click(object sender, EventArgs e) {
            templateList.Visible = true;
            groupsPanel.Visible = false;
            controlPanel.Visible = true;
            templateList.Select();
        }
      
        private void groupsList_SelectedIndexChanged(object sender, EventArgs e) {
            groupsApply.Enabled = groupsRemove.Enabled = (groupsList.SelectedItems.Count > 0);
            if (groupsList.SelectedItems.Count > 0) {
                groupsId.Text = groupsList.SelectedItems[0].Text;
                groupsName.Text = groupsList.SelectedItems[0].SubItems[1].Text;
            } else {
                groupsId.Text = groupsName.Text = String.Empty;
            }
        }

        private void groupsRemove_Click(object sender, EventArgs e) {
            while (groupsList.SelectedItems.Count > 0) {
                groupsList.Items.Remove(groupsList.SelectedItems[0]);
            }
        }

        private void groupsAdd_Click(object sender, EventArgs e) {
            ListViewItem newItem = new ListViewItem(groupsId.Text);
            newItem.SubItems.Add(groupsName.Text);
            groupsList.Items.Add(newItem);
            groupsList.Select();
        }

      

        private void Groups_Click(object sender, EventArgs e) {
            //Load Groups
            groupsList.Items.Clear();
            foreach (ListViewGroup g in templateList.Groups) {
                ListViewItem newItem = new ListViewItem(g.Name);
                newItem.SubItems.Add(g.Header);
                groupsList.Items.Add(newItem);
            }
            templateList.Visible = false;
            groupsPanel.Visible = true;
            controlPanel.Visible = false;
            groupsPanel.Dock = DockStyle.Fill;
            groupsList.Select();
        }

        private void groupsApply_Click(object sender, EventArgs e) {
            if (groupsList.SelectedItems.Count > 0) {
                groupsList.SelectedItems[0].Text = groupsId.Text;
                groupsList.SelectedItems[0].SubItems[1].Text = groupsName.Text;
            }
            groupsList.Select();
        }

        private void Templates_Click(object sender, EventArgs e) {
            editClear_Click(null, null);
            editGroup.Items.Clear();
            editGroup.Items.Add("None");
            foreach (ListViewGroup g in templateList.Groups) {
                editGroup.Items.Add(g.Name);
            }
            editGroup.SelectedIndex = 0;
            groupsList.Select();
            groupsPanel.Visible = false;
            controlPanel.Visible = false;
            this.Size = new System.Drawing.Size(this.Width, this.Height + 150);
     //       templateList.Height = 200;
           // templateList.Dock = DockStyle.Top;
            //editPanel.Dock = DockStyle.Fill;
            editPanel.Visible = true;
        

//            editGroup.BringToFront();
            //templateList.SendToBack();
         
        }

 

        private void editAdd_Click(object sender, EventArgs e) {
            ListViewItem newItem = new ListViewItem(editName.Text,0);
            newItem.SubItems.Add(editDescription.Text);
            newItem.SubItems.Add(editExtension.Text);

            //
            String FileName = String.Empty;
            if (System.IO.File.Exists(editFileName.Text)) {
                if (editFileName.Text != System.IO.Path.Combine(Plugin.templateDirectory, System.IO.Path.GetFileName(editFileName.Text))) {
                    System.IO.File.Copy(editFileName.Text, System.IO.Path.Combine(Plugin.templateDirectory, System.IO.Path.GetFileName(editFileName.Text)), true);
                }
                FileName = System.IO.Path.GetFileName(editFileName.Text);
            //} else if (System.IO.Path.GetDirectoryName(editFileName.Text) == Plugin.templateDirectory) {
                //FileName = System.IO.Path.GetFileName(editFileName.Text);
            }else if(System.IO.File.Exists( System.IO.Path.Combine( Plugin.templateDirectory , editFileName.Text))){
                   FileName = editFileName.Text;
            }
            newItem.SubItems.Add( FileName);



            newItem.SubItems.Add(editReplace.Text);

            templateList.Items.Add(newItem);
            if (editGroup.SelectedItem.ToString() == "None") {
                newItem.Group = null;
            } else {
                newItem.Group = templateList.Groups[editGroup.SelectedItem.ToString()];
            }
        }

        private void editCancel_Click(object sender, EventArgs e) {
            editPanel.Visible = false;
            controlPanel.Visible = true;

            templateList.Select();
            this.Size = new System.Drawing.Size(this.Width, this.Height - 150);
        }

        private void editSave_Click(object sender, EventArgs e) {
            XmlTextWriter xmlFile = new XmlTextWriter(Plugin.templateFile, System.Text.Encoding.UTF8);
            xmlFile.Formatting = Formatting.Indented;
            xmlFile.WriteStartElement("NotepadX");


            xmlFile.WriteStartElement("Groups");




            foreach (ListViewGroup g in templateList.Groups) {
                xmlFile.WriteStartElement("Group");
                xmlFile.WriteAttributeString("id", g.Name);
                xmlFile.WriteAttributeString("name", g.Header);
                xmlFile.WriteEndElement();
            }
            xmlFile.WriteEndElement(); // End of Groups
            xmlFile.WriteStartElement("Templates");

            foreach (ListViewItem item in templateList.Items) {
                xmlFile.WriteStartElement("Template");
                xmlFile.WriteAttributeString("name", item.Text);
                if (item.Group != null) {
                    xmlFile.WriteAttributeString("group", item.Group.Name);
                }else{
                    xmlFile.WriteAttributeString("group", String.Empty);
                }
                xmlFile.WriteAttributeString("description", item.SubItems[1].Text);
                xmlFile.WriteAttributeString("extension", item.SubItems[2].Text);
                xmlFile.WriteAttributeString("filename", item.SubItems[3].Text);
                xmlFile.WriteAttributeString("replaceWithFileName", item.SubItems[4].Text);
                xmlFile.WriteEndElement();
            }
            xmlFile.WriteEndElement(); // End of Templates


            xmlFile.WriteEndElement();
            xmlFile.Flush();
            xmlFile.Close();

            editPanel.Visible = false;
            controlPanel.Visible = true;

            templateList.Select();
            this.Size = new System.Drawing.Size(this.Width, this.Height - 150);
        }

        private void editRemove_Click(object sender, EventArgs e) {
            while (templateList.SelectedItems.Count > 0) {
                templateList.Items.Remove(templateList.SelectedItems[0]);
            }
        }

        private void editApply_Click(object sender, EventArgs e) {
            if (templateList.SelectedItems.Count > 0) {
                ListViewItem selected = templateList.SelectedItems[0];
                selected.Text = editName.Text;

                selected.SubItems[1].Text = editDescription.Text;
                selected.SubItems[2].Text = editExtension.Text;
             

                //
                String FileName = String.Empty;
                if (System.IO.File.Exists(editFileName.Text)) {
                    System.IO.File.Copy(editFileName.Text, System.IO.Path.Combine(Plugin.templateDirectory, System.IO.Path.GetFileName(editFileName.Text)));
                    FileName = System.IO.Path.GetFileName(editFileName.Text);
                } else if (System.IO.Path.GetDirectoryName(editFileName.Text) == Plugin.templateDirectory) {
                    FileName = System.IO.Path.GetFileName(editFileName.Text);
                } else if (System.IO.File.Exists(System.IO.Path.Combine(Plugin.templateDirectory, editFileName.Text))) {
                    FileName = editFileName.Text;
                }
                selected.SubItems[3].Text = FileName;


                selected.SubItems[4].Text = editReplace.Text;

                if (editGroup.SelectedItem.ToString() == "None") {
                    selected.Group = null;
                } else {
                   selected.Group = templateList.Groups[editGroup.SelectedItem.ToString()];
                }


            }
        }

        private void editFileBrowse_Click(object sender, EventArgs e) {
            OpenFileDialog d = new OpenFileDialog();
            d.InitialDirectory = Plugin.templateDirectory;
            d.CheckFileExists = true;
            d.Multiselect = false;
            d.Filter = "All files (*.*)|*.*";
            if (d.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) {
                editFileName.Text = d.FileName;
            }

        }

        private void editClear_Click(object sender, EventArgs e) {
            editGroup.SelectedIndex = 0;
            
            templateList.SelectedItems.Clear();
            templateList.Select();
            editName.Text = editDescription.Text = editExtension.Text = editFileName.Text = editReplace.Text = String.Empty;
        }

        private void templateList_MouseDoubleClick(object sender, MouseEventArgs e) {
       
            if (templateList.SelectedItems.Count > 0) {
                open_Click(null, null);
            }
        }

  
    }
}
